package com.wanye;

import com.google.common.cache.CacheLoader;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.wanye.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.guava.GuavaCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

/**
 * Created by wanye on 2017/10/27.
 */
@Configuration
public class GuavaCacheConfig {

    private ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));

    @Value("${spring.cache.guava.spec}")
    private String spec;

    @Autowired
    UserService userService;

    @Bean(name = "local")
    public CacheManager cacheManager() {
        GuavaCacheManager guavaCacheManager = new GuavaCacheManager();
        guavaCacheManager.setCacheSpecification(spec);

        guavaCacheManager.setCacheLoader(new CacheLoader<Object, Object>() {
            @Override
            public Object load(Object key) throws Exception {
                return userService.getTeacherById(Integer.parseInt(key.toString()));
            }

            @Override
            public ListenableFuture<Object> reload(final Object key, Object oldValue) throws Exception {
//                Object o = userService.getTeacherById(Integer.parseInt(key.toString()));
//                return Futures.immediateFuture(o);
                return executorService.submit(new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        return userService.getTeacherById(Integer.parseInt(key.toString()));
                    }
                });
            }
        });

        return guavaCacheManager;
    }
}
